use std::path::Path;
use std::fmt;
use chrono::{Local, Utc};

cfg_if::cfg_if! {
    if #[cfg(target_arch = "wasm32")] {
        use web_sys::console;
        use wasm_bindgen::{JsValue};
    } else {
        use ansi_term::Color;
    }
}

#[derive(Copy, Clone, Debug)]
pub enum Timezone {
    None,
    Utc,
    Local,
}

static DEFAULT_TIME_FORMAT: &str = "%Y-%m-%d %H:%M:%S";

pub fn format_time(timezone: &Timezone) -> String {
    match timezone {
        Timezone::None => "".to_string(),
        Timezone::Local => format!("{} ", Local::now().format(DEFAULT_TIME_FORMAT)),
        Timezone::Utc => format!("{} ", Utc::now().format(DEFAULT_TIME_FORMAT)),
    }
}

pub fn format_path(path: &str, line: u32) -> String {
    let pathname = Path::new(path);
    let pathname = pathname.to_str().unwrap_or("???");
    // pathname.to_string().splitn(3, "/");
    // let pathname = path.file_stem().unwrap().to_owned().into_string().unwrap();
    // let pathname = pathname.file_name().unwrap().to_owned().into_string().unwrap();
    let pathname = format!("{}:{}", pathname, line);
    pathname
}

pub fn __print_val(path: &str, line: u32, args: fmt::Arguments) {
    #[cfg(target_arch = "wasm32")]
    {
        let path_str = format_path(path, line);
        let msg = format!("{}", args);

        console::log_4(
            &JsValue::from(format!("%c{}%c {} %c{}",
                                   "VALUE", path_str, msg
            )),
            &JsValue::from("color: white; background: #b100f3"),
            &JsValue::from("color: inherit"),
            &JsValue::from("color: #b100f3"),
        );
    }

    #[cfg(not(target_arch = "wasm32"))]
    {
        let timestamp = format_time(&Timezone::Local);
        let mut path_str = format_path(path, line);

        // timestamp = Color::Fixed(250).paint(timestamp).to_string();
        path_str = Color::Blue.paint(path_str).to_string();

        let mut color_msg = format!("{}", args);
        color_msg = Color::Purple.paint(color_msg).to_string();

        let message = format!("{}{} {}", timestamp, path_str, color_msg);
        println!("{}", message);
    }
}

